package com.michale.framework.security.service.impl;

import com.michale.common.constants.CommonConstant;
import com.michale.common.constants.UserConstant;
import com.michale.common.domain.permissions.UserEntity;
import com.michale.common.utils.String.StringUtils;
import com.michale.common.utils.i18n.MessageUtils;
import com.michale.common.utils.security.SecurityUtils;
import com.michale.framework.config.async.asyncFactory.AsyncTask;
import com.michale.framework.config.async.manager.AsyncManager;
import com.michale.framework.security.service.LoginService;
import com.michale.framework.security.service.RegisterService;
import com.michale.system.service.ConfigService;
import com.michale.system.service.UserService;
import com.michale.system.vo.register.RegisterBody;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Michale
 * @apiNote 注册校验
 */
@Service("registerService")
public class RegisterServiceImpl implements RegisterService {

    @Resource
    private LoginService loginService;
    @Resource
    private ConfigService configService;
    @Resource
    private UserService userService;

    /**
     * 注册校验
     *
     * @param registerBody 注册信息
     * @return 注册结果信息
     */
    @Override
    public String register(RegisterBody registerBody) {
        String msg = "", username = registerBody.getUserName(), password = registerBody.getPassword();
        UserEntity userEntity = new UserEntity();
        userEntity.setUserName(username);
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        // 验证码开关
        if (captchaEnabled) {
            loginService.validateCaptcha(registerBody.getCode(), registerBody.getUuid());
        }

        if (StringUtils.isEmpty(username)) {
            msg = "用户名不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (username.length() < UserConstant.USERNAME_MIN_LENGTH
                || username.length() > UserConstant.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (password.length() < UserConstant.PASSWORD_MIN_LENGTH
                || password.length() > UserConstant.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (UserConstant.NOT_UNIQUE.equals(userService.checkUserNameUnique(userEntity))) {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        } else {

            userEntity.setNickName(username);
            userEntity.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));
            boolean regFlag = userService.registerUser(userEntity);
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                AsyncManager.asyncManager().start(AsyncTask.recordLoginInfo(username,CommonConstant.REGISTER,MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }
}
